//客户端编写
#include <iostream>
#include <string>

#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

#include "Logger.hpp"
Logger& Log = Logger::GetInstance();

//退出错误码
enum
{
    SOCK_FAILED = 1,
    BIND_FAILED = 2
};

//使用说明
void Usage(const std::string& proc){
    std::cout << "Usage: " << proc << " ServerIP Port" << std::endl;
}
int main(int argc, char* argv[]){
    if(argc != 3){
        Usage(argv[0]);
        exit(0);
    }
    //获取服务器IP
    std::string ServerIP(argv[1]);
    uint16_t ServerPort = std::stoi(argv[2]);

    //定义服务器的sockaddr
    struct sockaddr_in server_sockaddr;
    memset(&server_sockaddr, 0, sizeof(server_sockaddr));
    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_port = htons(ServerPort);
    server_sockaddr.sin_addr.s_addr = inet_addr(ServerIP.c_str());
    socklen_t server_sockaddr_len = sizeof(server_sockaddr);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        Log(Fatal, "socket filled");
        exit(SOCK_FAILED);
    }

    while(true){
        //输入信息
        std::cout << "Please enter message: ";
        std::string msg;
        getline(std::cin, msg);

        if(msg.empty()){
            continue;
        }
        
        //发送信息
        int send_num = sendto(sockfd, msg.c_str(), msg.size(), 0, 
        (const struct sockaddr*)&server_sockaddr, server_sockaddr_len);
        if(send_num < 0){
            Log(Warning, "Send failed");
            continue;
        }

        //无用的sockaddr
        struct sockaddr_in temp_sockaddr;
        socklen_t temp_sockaddr_len = sizeof(temp_sockaddr);

        char response_buffer[4096] = { 0 };
        int recv_num = recvfrom(sockfd, response_buffer, sizeof(response_buffer) - 1, 0,
        (struct sockaddr*)&temp_sockaddr, &temp_sockaddr_len);
        if (recv_num < 0){
            Log(Warning, "recvfrom failed");
            continue;
        }

        if (recv_num > 0) {
            // [修正] 打印服务器的响应
            response_buffer[recv_num] = '\0'; // 确保字符串结束
            std::cout << response_buffer << std::endl;
        }
    }

    close(sockfd);
    return 0;
}